import { login, logout, getInfo, getRoutes } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,constantRoutes,otherRoutes } from '@/router';
import Layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user:{},
    roles:[],
    isFirstLogin:false,
    // sidebarRouters: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER:( state, user )=>{
    state.user = user
  },
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes
  },
  SET_ROLES:( state, roles )=>{
    state.roles = roles
  },
  SET_ISFIRSTLOGIN:(state, isboole) => {
    state.isFirstLogin = isboole
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
         console.log('response:',response);
          const { data } = response
          commit('SET_TOKEN', data);
          commit('SET_ISFIRSTLOGIN',true);
          setToken(data)
          resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // commit('SET_NAME', 'admin');
      // resolve();
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          return reject('验证失败，请重新登录')
        }
        localStorage.setItem('uid',data.id);
        commit('SET_NAME', data.user_login);
        let user = data.info;
        if(user){
          commit('SET_USER', {...user,user_login:data.user_login});
        }else{
          commit('SET_USER', {
            id:data.id,
            user_login:data.user_login
          });
        }
        // commit('SET_ROLES',user.role.map(item=>item.role_id));
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE');
        localStorage.removeItem('uid');
        localStorage.clear();
        commit('SET_NAME', '');
        commit('SET_USER', {});
        commit('SET_ROLES', []);
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit,dispatch }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE');
      commit('SET_NAME', '');
      commit('SET_USER', {});
      localStorage.removeItem('uid');
      localStorage.clear();
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },


  getRoutes({commit, state}){
    return new Promise((resolve, reject) => {
      getRoutes().then(response => {
        const { data } = response;
        let nrouterList = JSON.parse(JSON.stringify(otherRoutes));
        let routerNameList = data.map(item=>item.indexTmp);
        // console.log('routerNameList:',routerNameList);
        let sidebarRoutes = filterTree(nrouterList,routerNameList);
        console.log('sidebarRoutes:',sidebarRoutes);
        sidebarRoutes = constantRoutes.concat(sidebarRoutes);
        sidebarRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // filterRouter(nrouterList,routerNameList);
        // console.log('nrouterList:',nrouterList);
        // commit('SET_SIDEBAR_ROUTERS',nrouterList)
        commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
        resolve(sidebarRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  }

};

//   // 遍历数据
// function filterRouter(data,item){
//   data.forEach(ditem=>{
//       // if(ditem){
//       if(item.indexTmp == ditem.name){
//         ditem.hidden = true;
//       }
//       // }
//     if(ditem.children && ditem.children.length > 0){
//       filterRouter(ditem.children,item);
//     }
//   })
// };

// 将没有的路由过滤
function filterRouter(router,namelist,){
  router.forEach(ditem=>{
      // 如果没有找到
      if(namelist.indexOf(ditem.name)===-1){
        ditem.hidden = true;
        if(ditem.meta){
          ditem.meta.auth = false;
          console.log('auth11:',ditem);
        }
      }
      if(ditem.children && ditem.children.length > 0){
        filterRouter(ditem.children,namelist);
      }
  })
};


function filterTree (tree = [], map = [], arr = []) {
  if (!tree.length) return []
  for (let item of tree) {
    if (!map.includes(item.name)) continue
    let node = {...item}
    if (node.component) {
      // Layout ParentView 组件特殊处理
      if(node.component === 'Layout') {
        node.component = Layout
      }else {
        node.component = loadView(node.component)
      }
    }
    arr.push(node)
    if (item.children && item.children.length){
      node.children = [];
      filterTree(item.children, map, node.children)
    } 
  }
  return arr
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

